import fs from 'fs';
import path from 'path';
import { fetchOneFile } from '../../utils/file.util';
import { ErrorLog, GlobalData } from '../../utils/data.util';
import { BASE_DIST, BASE_FROM } from '../../constant';

const errorLog = new ErrorLog();
const globalData = new GlobalData({
  dist: BASE_DIST,
  from: BASE_FROM,
  transFileDist: (url: string) => {
    return path.basename(url);
  }
});


export async function downOneImg(imgUrl: string) {
  const arrayBuffer = await fetchOneFile(imgUrl);
  if (!arrayBuffer) {
    errorLog.addLog(imgUrl + '文件获取失败\n');
    return;
  }
  return fs.promises.writeFile(path.join(globalData.data.dist, globalData.data.transFileDist(imgUrl)), arrayBuffer);
}

export const main = (getImgFun: () => string[]) => {
  const downPromiseArr = getImgFun().map(item => (downOneImg(item)));
  return Promise.all(downPromiseArr).finally(() => {
    globalData.resetData();
  });
};
